#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
渐进式数据管理器
实现每秒返回Delta/Theta数据，5秒预热后开始脑状态分析
"""

import time
from collections import deque
from typing import Dict, List, Optional, Any
from datetime import datetime
from models.brain_state_models import BrainWaveRatesInput

class ProgressiveDataManager:
    """
    渐进式数据管理器
    
    职责：
    1. 管理每秒的Delta/Theta数据
    2. 维护5秒滑动窗口
    3. 控制脑状态分析触发时机
    4. 提供预热进度信息
    """
    
    def __init__(self, session_id: str, warmup_seconds: int = 5):
        """
        初始化渐进式数据管理器
        
        Args:
            session_id: 会话ID
            warmup_seconds: 预热时间（秒），默认5秒
        """
        self.session_id = session_id
        self.warmup_seconds = warmup_seconds
        self.data_buffer = deque(maxlen=warmup_seconds)  # 5秒滑动窗口
        self.start_time = None
        self.last_analysis_time = None
        self.is_warmup_complete = False
        
    def add_data_point(self, wave_data: Dict[str, Any]) -> None:
        """
        添加每秒的数据点
        
        Args:
            wave_data: 包含delta, theta, alpha, beta, gamma等频段数据
        """
        if self.start_time is None:
            self.start_time = time.time()
        
        current_time = time.time()
        
        data_point = {
            'timestamp': current_time,
            'delta': wave_data.get('delta', 0),
            'theta': wave_data.get('theta', 0),
            'alpha': wave_data.get('alpha', 0),
            'beta': wave_data.get('beta', 0),
            'gamma': wave_data.get('gamma', 0),
            'poor_signal': wave_data.get('poor_signal', 200),
            'attention': wave_data.get('attention', 0),
            'meditation': wave_data.get('meditation', 0)
        }
        
        self.data_buffer.append(data_point)
        
        # 检查预热是否完成
        if not self.is_warmup_complete:
            elapsed_time = current_time - self.start_time
            if elapsed_time >= self.warmup_seconds and len(self.data_buffer) >= self.warmup_seconds:
                self.is_warmup_complete = True
    
    def can_analyze_brain_state(self) -> bool:
        """
        检查是否可以进行脑状态分析
        
        Returns:
            bool: 是否可以进行状态分析
        """
        if not self.is_warmup_complete:
            return False
        
        # 检查数据缓冲区是否有足够数据
        if len(self.data_buffer) < self.warmup_seconds:
            return False
        
        # 检查信号质量（最近3个数据点的平均质量）
        recent_data = list(self.data_buffer)[-3:]
        if recent_data:
            avg_signal_quality = sum(d['poor_signal'] for d in recent_data) / len(recent_data)
            if avg_signal_quality > 100:  # 信号质量差
                return False
        
        return True
    
    def get_warmup_progress(self) -> Dict[str, Any]:
        """
        获取预热进度信息
        
        Returns:
            Dict: 包含预热进度的信息
        """
        if self.start_time is None:
            return {
                'percentage': 0.0,
                'remaining_seconds': self.warmup_seconds,
                'status': 'not_started',
                'message': '等待开始...'
            }
        
        current_time = time.time()
        elapsed_time = current_time - self.start_time
        
        if self.is_warmup_complete:
            return {
                'percentage': 100.0,
                'remaining_seconds': 0.0,
                'status': 'completed',
                'message': '预热完成，开始分析'
            }
        
        progress_percentage = min((elapsed_time / self.warmup_seconds) * 100, 100.0)
        remaining_seconds = max(0, self.warmup_seconds - elapsed_time)
        
        return {
            'percentage': round(progress_percentage, 1),
            'remaining_seconds': round(remaining_seconds, 1),
            'status': 'warming_up',
            'message': f'正在收集数据... ({progress_percentage:.1f}%)'
        }
    
    def get_latest_wave_data(self) -> Optional[Dict[str, Any]]:
        """
        获取最新的波段数据
        
        Returns:
            Dict: 最新的波段数据，如果没有数据则返回None
        """
        if not self.data_buffer:
            return None
        
        latest_data = self.data_buffer[-1]
        signal_status = self._get_signal_status(latest_data['poor_signal'])
        
        return {
            'timestamp': latest_data['timestamp'],
            'delta': latest_data['delta'],
            'theta': latest_data['theta'],
            'alpha': latest_data['alpha'],
            'beta': latest_data['beta'],
            'gamma': latest_data['gamma'],
            'poor_signal': latest_data['poor_signal'],
            'signal_status': signal_status,
            'attention': latest_data['attention'],
            'meditation': latest_data['meditation']
        }
    
    def get_analysis_data(self) -> Optional[BrainWaveRatesInput]:
        """
        获取用于脑状态分析的数据
        
        Returns:
            BrainWaveRatesInput: 用于状态分析的数据，如果不能分析则返回None
        """
        if not self.can_analyze_brain_state():
            return None
        
        # 构造BrainWaveRatesInput格式
        buffer_data = list(self.data_buffer)
        
        relative_rates = {
            'delta': [d['delta'] for d in buffer_data],
            'theta': [d['theta'] for d in buffer_data],
            'alpha': [d['alpha'] for d in buffer_data],
            'beta': [d['beta'] for d in buffer_data],
            'gamma': [d['gamma'] for d in buffer_data]
        }
        
        start_time = datetime.fromtimestamp(buffer_data[0]['timestamp']).isoformat()
        end_time = datetime.fromtimestamp(buffer_data[-1]['timestamp']).isoformat()
        
        return BrainWaveRatesInput(
            session_id=self.session_id,
            start_time=start_time,
            end_time=end_time,
            relative_rates=relative_rates
        )
    
    def _get_signal_status(self, poor_signal: int) -> Dict[str, Any]:
        """
        根据信号质量值判断信号状态
        
        Args:
            poor_signal: 信号质量值 (0-255, 0为最好，255为最差)
            
        Returns:
            Dict: 包含信号状态信息
        """
        if poor_signal == 0:
            status = "excellent"
            description = "信号质量极佳"
            color = "green"
        elif poor_signal <= 25:
            status = "good"
            description = "信号质量良好"
            color = "green"
        elif poor_signal <= 50:
            status = "fair"
            description = "信号质量一般"
            color = "yellow"
        elif poor_signal <= 100:
            status = "poor"
            description = "信号质量较差"
            color = "orange"
        elif poor_signal <= 200:
            status = "very_poor"
            description = "信号质量很差，请调整设备位置"
            color = "red"
        else:
            status = "no_signal"
            description = "无信号或设备未正确佩戴"
            color = "red"
        
        return {
            "status": status,
            "description": description,
            "color": color,
            "value": poor_signal,
            "device_connected": poor_signal < 200  # 信号质量<200认为设备正常连接
        }
    
    def should_auto_disconnect(self) -> bool:
        """
        检查是否应该自动断开连接
        基于最近几个数据点的信号质量判断
        
        Returns:
            bool: 是否应该自动断开
        """
        if len(self.data_buffer) < 3:
            return False
        
        # 检查最近3个数据点的信号质量
        recent_data = list(self.data_buffer)[-3:]
        poor_signals = [d['poor_signal'] for d in recent_data]
        
        # 如果连续3次信号质量都>=200，建议断开
        return all(signal >= 200 for signal in poor_signals)
    
    def get_connection_status(self) -> Dict[str, Any]:
        """
        获取设备连接状态信息
        
        Returns:
            Dict: 连接状态信息
        """
        if not self.data_buffer:
            return {
                "connected": False,
                "status": "no_data",
                "description": "暂无数据"
            }
        
        latest_data = self.data_buffer[-1]
        signal_status = self._get_signal_status(latest_data['poor_signal'])
        should_disconnect = self.should_auto_disconnect()
        
        return {
            "connected": signal_status["device_connected"] and not should_disconnect,
            "signal_quality": signal_status,
            "should_auto_disconnect": should_disconnect,
            "last_update": latest_data['timestamp']
        }
    
    def reset(self) -> None:
        """
        重置管理器状态
        """
        self.data_buffer.clear()
        self.start_time = None
        self.last_analysis_time = None
        self.is_warmup_complete = False
    
    def get_status_summary(self) -> Dict[str, Any]:
        """
        获取当前状态摘要
        
        Returns:
            Dict: 包含当前状态的摘要信息
        """
        return {
            'session_id': self.session_id,
            'warmup_seconds': self.warmup_seconds,
            'is_warmup_complete': self.is_warmup_complete,
            'data_points_count': len(self.data_buffer),
            'can_analyze': self.can_analyze_brain_state(),
            'warmup_progress': self.get_warmup_progress(),
            'latest_data_available': self.get_latest_wave_data() is not None
        }